require 'libxml'

class BnfController < ApplicationController
  autocomplete :bnf, :h0001
  def analyze
    require 'libxml'
    dn ='marc:http://www.loc.gov/MARC21/slim'
    xml_document = LibXML::XML::Document.file('/home/stephan/workspace/RISMToolKit/app/models/test.xml')
    if params["extext"]
      rismid=params["extext"]["name"]
    end
    book_xpath = '//marc:record'
    nodes=xml_document.find(book_xpath,dn)
    @countnodes=nodes.size
    @res={}
    nodes.each {|record| record.each {|node|
        node.attributes.each{|att|
          tag=node.attributes[att.name] if att.name=="tag"
          if !@res.key?(tag)
            @res[tag]=[]
          end
          node.children.each{|subf|
            if subf.name=="subfield"
              subf.attributes.each {
                |atts| @res[tag] <<subf.attributes[atts.name] if atts.name=="code" and !@res[tag].include?(subf.attributes[atts.name])
              }
            end
          }
        }
      }
    }
    @endlist=[]
    @res.keys.each{|k| @endlist << k if k}
    @el=@endlist.sort
  end

  def changelog
  end

  def showsubfield
    if params[:subfield]
      @subfield=params[:subfield]
      @tag=@subfield.split('$')[0]
      @code=@subfield.split('$')[1]
      @mydict=[]
      dn ='marc:http://www.loc.gov/MARC21/slim'
      xml_document = LibXML::XML::Document.file('/home/dev/projects/rismtoolkit/app/models/mybnfout.xml')
      id='//marc:controlfield[@tag=001]/text()' 
      field = '//marc:datafield[@tag="'+String(@tag)+'"]/marc:subfield[@code="'+String(@code)+'"]/text()'
      @nodes={}
      @keys=xml_document.find('//marc:record', dn)
      @keys.each do |k|
      if LibXML::XML::Document.string(k.to_s).find(field,dn).to_a[0]
        @nodes[LibXML::XML::Document.string(k.to_s).find(id,dn).to_a[0]]=LibXML::XML::Document.string(k.to_s).find(field,dn).to_a[0]
      end
      end
      @countno=@nodes.size if @nodes.size > 0
    end
  end

  def populate
    #rismid="FRBNF395788690000002"
    dn ='marc:http://www.loc.gov/MARC21/slim'
    xml_document = LibXML::XML::Document.file('/home/stephan/workspace/RISMToolKit/app/models/test.xml')
    #if params["extext"]
    #  rismid=params["extext"]["name"]
    #end
    #book_xpath = '//marc:record/marc:controlfield[@tag="001"][contains(.,"'+rismid+'")]/..'
    #nodes=xml_document.find(book_xpath,dn)
    #@old_xml=nodes[0]
    #x=Rismid.find(:first, :conditions=>"h0001='B00340000'").xml
    #@old_xml=LibXML::XML::Document.string(x)

    #@ids=xml_document.find('//marc:record/marc:controlfield[@tag="001"]/text()',dn).to_a.select {|s| !s.to_s.start_with?('4')}i

    @ids=xml_document.find('//marc:record',dn)
    @ids.each {|r|
      coll=r.find('marc:datafield/marc:subfield[@code="9"]',dn)
      url=r.find('marc:controlfield[@tag="009"]',dn)
      signa=r.find('marc:datafield[@tag="930"]/marc:subfield[@code="a"]',dn)
      ms=r.find('marc:datafield[@tag="205"]',dn)
      if coll.length<1
        rismid=String(r.find('marc:controlfield[@tag="001"]/text()',dn)[0])
        
        LibXML::XML::Namespace.new(r, nil, 'http://www.loc.gov/MARC21/slim')
        #p r.namespaces.namespace
        #bwv=String(r.find('marc:datafield[@tag="240"]/marc:subfield[@code="n"]/text()',dn)[0])
        xml=r.to_s()
        n=Bnf.new(:h0001=>rismid, :xml=>xml)
        n.save
      else
        myhash=Hash.new{|h, k| h[k] = []}
        rismid=String(r.find('marc:controlfield[@tag="001"]/text()',dn)[0])
        coll=r.find('marc:datafield/marc:subfield[@code="9"]/..',dn)
        haupt=r.to_a - coll.to_a
        haupt.reject! { |c| c.empty? }
        coll.each {|tag|
            key=tag.find('marc:subfield[@code="9"]/text()', dn)[0]
            myhash[key.to_s] << tag
          }
        #p myhash
        myhash.each {|k|
          e_xml=LibXML::XML::Document.new()
          e_xml.root = LibXML::XML::Node.new("record")
          LibXML::XML::Namespace.new(e_xml.root, nil, 'http://www.loc.gov/MARC21/slim')
          e_xml.root  << field=LibXML::XML::Node.new("leader")
          field.content="00910cdd#a2200253###4500"
          e_xml.root << field=LibXML::XML::Node.new("controlfield")
          field['tag']='001'
          field.content=rismid+k[0].to_s
          if url[0]
            url_node=e_xml.import(url[0])
            e_xml.root << url_node
          end
          if ms[0]
            ms_node=e_xml.import(ms[0])
            e_xml.root << ms_node
          end
 
          k[1].each { |v|
            new_node=e_xml.import(v)
            #p "einzel: "+new_node.namespaces.namespace.to_s
            e_xml.root << new_node
              }
          e_xml.root << field=LibXML::XML::Node.new("datafield")
          LibXML::XML::Namespace.new(field, nil, 'http://www.loc.gov/MARC21/slim')
          field['tag']='773'
          field['ind1']=" "
          field['ind2']=" "
          field << sub=LibXML::XML::Node.new("subfield")
          sub['code']='a'
          sub.content=rismid
          if signa[0]
            signa_node=e_xml.import(signa[0])
            e_xml.root << signa_node
          end
 
          #p e_xml
          n=Bnf.new(:h0001=>rismid+k[0].to_s, :xml=>e_xml.to_s)
          n.save
          }
        
        h_xml=LibXML::XML::Document.new()
        h_xml.root = LibXML::XML::Node.new("record")
        LibXML::XML::Namespace.new(h_xml.root, nil, 'http://www.loc.gov/MARC21/slim')
        haupt.each {|k|
            new_node=h_xml.import(k)
            #p "haupt: "+new_node.namespaces.namespace.to_s
            h_xml.root << new_node
          }
        n=Bnf.new(:h0001=>rismid, :xml=>h_xml.to_s)
        n.save
 
        #p h_xml
        
    #Es werden subfields durchsucht, die code="9" enthalten. Jedes datafield mit code="9" soll selektiert werden, jedes datafield ohne code="9" ebenfalls. Alle Knoten mit code="9" sind Einzeleinträge, Knoten ohne code="9" sind Haupteinträge.
      end
    }
  end

  def convert
    require 'MarcTools'
        dn ='marc:http://www.loc.gov/MARC21/slim'
        rismid="FRBNF395788690000002"
        if params["extext"]
          rismid=params["extext"]["name"]
        end
        x=Bnf.find(:first, :conditions=>"h0001='"+rismid+"'")
        if x
          x=x.xml
        @old_xml=LibXML::XML::Document.string(x).root
        @url=String(@old_xml.find('marc:controlfield[@tag="009"]/text()', 'marc:http://www.loc.gov/MARC21/slim')[0])
        converter=MarcTools::MarcConverter.new
        @marc_hash=converter.marc_to_hash(@old_xml)      
    @marc_hash=converter.changeTag(@marc_hash,'036', '031')
    @marc_hash=converter.changeTag(@marc_hash,'500', '240')
    @marc_hash=converter.changeSubfieldCode(@marc_hash,'240$r', '240$m')
    @marc_hash=converter.changeSubfieldCode(@marc_hash,'240$s', '240$n')
    @marc_hash=converter.changeSubfieldCode(@marc_hash,'240$u', '240$r')
    #@marc_hash=converter.removeTag(@marc_hash,'500')
    @marc_hash=converter.updateElements(@marc_hash,'031$a', lambda { |a| a[1..-1]})
    @marc_hash=converter.updateElements(@marc_hash,'031$b', lambda { |a| a[1..-1]})
    @marc_hash=converter.updateElements(@marc_hash,'031$c', lambda { |a| a[1..-1]})
    @marc_hash=converter.concat(@marc_hash,'700$a', '700$b', ", ") if @marc_hash['700']
    @marc_hash=converter.removeSubfield(@marc_hash,'700$b')
    @marc_hash=converter.changeSubfieldCode(@marc_hash,'700$f', '700$d')
    @marc_hash=converter.changeTag(@marc_hash,'700', '100')
    @marc_hash=converter.changeTag(@marc_hash,'930', '852')
    @marc_hash=converter.changeTag(@marc_hash,'931', '591')
    @marc_hash=converter.changeSubfieldCode(@marc_hash,'852$a', '852$c')
    @marc_hash=converter.insertTag(@marc_hash,'852$a', 'F-Pn')
    @marc_hash=converter.changeTag(@marc_hash,'200', '245')    
    @marc_hash=converter.changeTag(@marc_hash,'101', '041')
    @marc_hash=converter.changeTag(@marc_hash,'300', '500')
    @marc_hash=converter.insertTag(@marc_hash,'500$a', 'Original catalog entry: '+@url)
    @marc_hash=converter.removeTag(@marc_hash,'009')      
    @marc_hash=converter.insertTag(@marc_hash,'500$a', converter.getElements(@marc_hash, '010$d').join("; ")) if converter.getElements(@marc_hash, '010$d')  
    @marc_hash=converter.removeTag(@marc_hash,'021')      
    @marc_hash=converter.removeTag(@marc_hash,'039')      
    @marc_hash=converter.insertTag(@marc_hash,'500$a', "Publisher number: "+converter.getElements(@marc_hash, '071$a').join("; ")) if converter.getElements(@marc_hash, '071$a')  
    @marc_hash=converter.removeTag(@marc_hash,'071')      
    @marc_hash=converter.removeTag(@marc_hash,'102')
    @marc_hash=converter.removeTag(@marc_hash,'106')
    @marc_hash=converter.removeTag(@marc_hash,'125')
    # b? as scoring
    @marc_hash=converter.removeSubfield(@marc_hash,'128$b')
    @marc_hash=converter.changeTag(@marc_hash,'128', '047')
    @marc_hash=converter.removeTag(@marc_hash,'140')      
    @marc_hash=converter.removeTag(@marc_hash,'145')    
    @marc_hash=converter.changeTag(@marc_hash,'205', '593')
    #@marc_hash=converter.insertTag(@marc_hash,'500$a', converter.getElements(@marc_hash,'300$a').join("; ")) if converter.getElements(@marc_hash, '300$a')  
    @marc_hash=converter.changeTag(@marc_hash,'210', '260')
    @marc_hash=converter.changeSubfieldCode(@marc_hash,'260$c', '260$b')
    @marc_hash=converter.changeSubfieldCode(@marc_hash,'260$d', '260$c')
    @marc_hash=converter.insertTag(@marc_hash,'300$a', converter.getElements(@marc_hash,'215$a').join("; ")) if converter.getElements(@marc_hash, '215$a')  
    @marc_hash=converter.insertTag(@marc_hash,'300$b', converter.getElements(@marc_hash,'215$c').join("; ")) if converter.getElements(@marc_hash, '215$c')  
    @marc_hash=converter.insertTag(@marc_hash,'300$c', converter.getElements(@marc_hash,'215$d').join("; ")) if converter.getElements(@marc_hash, '215$d')  
    @marc_hash=converter.removeTag(@marc_hash,'215')
    @marc_hash=converter.removeTag(@marc_hash,'208')
    @marc_hash=converter.insertTag(@marc_hash,'500$a', converter.getElements(@marc_hash,'307$a').join("; "))  if converter.getElements(@marc_hash, '307$a')  
    @marc_hash=converter.removeTag(@marc_hash,'307')
    @marc_hash=converter.removeTag(@marc_hash,'312')      
    marc_hash=converter.insertTag(@marc_hash,'500$a', converter.getElements(@marc_hash,'316$a').join("; "))  if converter.getElements(@marc_hash, '316$a')  
    @marc_hash=converter.removeTag(@marc_hash,'316')    
    @marc_hash=converter.insertTag(@marc_hash,'500$a', converter.getElements(@marc_hash,'319$a').join("; "))  if converter.getElements(@marc_hash, '319$a')  
    @marc_hash=converter.insertTag(@marc_hash,'500$a', converter.getElements(@marc_hash,'319$v').join("; "))  if converter.getElements(@marc_hash, '319$v')  
    @marc_hash=converter.removeTag(@marc_hash,'319')    
    @marc_hash=converter.changeTag(@marc_hash,'321', '510')
    @marc_hash=converter.changeTag(@marc_hash,'327', '505')
    @marc_hash=converter.removeTag(@marc_hash,'461')      
    @marc_hash=converter.changeTag(@marc_hash,'464', '245')      
    @marc_hash=converter.removeTag(@marc_hash,'517')      
    @marc_hash=converter.removeTag(@marc_hash,'519')      
    @marc_hash=converter.removeTag(@marc_hash,'540')      
    @marc_hash=converter.removeTag(@marc_hash,'600')      
    @marc_hash=converter.changeTag(@marc_hash,'606', '650')
    @marc_hash=converter.removeTag(@marc_hash,'620')      
    @marc_hash=converter.concat(@marc_hash,'701$a', '701$b', ", ") if @marc_hash['701']
    @marc_hash=converter.removeSubfield(@marc_hash,'701$b')
    @marc_hash=converter.changeSubfieldCode(@marc_hash,'701$f', '701$d')
    @marc_hash=converter.changeTag(@marc_hash,'701', '100')
    @marc_hash=converter.removeTag(@marc_hash,'701')
    @marc_hash=converter.concat(@marc_hash,'702$a', '702$b', ", ") if @marc_hash['702']
    @marc_hash=converter.removeSubfield(@marc_hash,'702$b')
    @marc_hash=converter.changeSubfieldCode(@marc_hash,'702$f', '702$d')
    @marc_hash=converter.changeTag(@marc_hash,'702', '700')
    @marc_hash=converter.removeTag(@marc_hash,'702')
    @marc_hash=converter.changeTag(@marc_hash,'712', '710')
    @marc_hash=converter.removeTag(@marc_hash,'722')      
    @marc_hash=converter.removeTag(@marc_hash,'801')
    @marc_hash=converter.removeTag(@marc_hash,'915')
    @marc_hash=converter.removeTag(@marc_hash,'917')
    @marc_hash=converter.removeTag(@marc_hash,'919')
    #@marc_hash=converter.insertTag(@marc_hash,'500$a', converter.getElements(@marc_hash,'930$e').join("; "))  if converter.getElements(@marc_hash, '930$e')  
    @marc_hash=converter.removeTag(@marc_hash,'930')
    @marc_hash=converter.removeTag(@marc_hash,'990')
    @new_xml=converter.hash_to_marc(@marc_hash)
      end
      end

  def retrieveFile
    require 'MarcTools'
        #rismid="B00340000"
        x=Rismid.find(:all, :conditions => ["h0001 not LIKE ?", "#{4}%"])
        #x=Rismid.find(:first, :conditions=>"h0001='"+rismid)
        x.each {|tempxml| 
          tempxmlx=tempxml.xml
        @old_xml=LibXML::XML::Document.string(tempxml).root
        @url=String(@old_xml.find('datafield[@tag="856"]/subfield[@code="u"]/text()')[0])
        converter=MarcTools::MarcConverter.new
        @marc_hash=converter.marc_to_hash(@old_xml)
        @marc_hash=converter.changeSubfieldCode(@marc_hash,'650$3', '650$a')
        @marc_hash=converter.moveTag(@marc_hash,'240$n', '240$a')
        @marc_hash=converter.moveTag(@marc_hash,'300$c', '300$a')
        @marc_hash=converter.removeTagbyValue(@marc_hash,'700$a', 'unbekannt')
        @marc_hash=converter.removeTagbyValue(@marc_hash,'657$y', 'unbekannt')
        @new_xml=converter.hash_to_marc(@marc_hash)
        p @new_xml
        }
      end
    

end

